package com.algorithm.List;

public class ArrayList<E> extends AbstractList<E>{
    private E[] elements;
    private static final int DEFAULT_CAPACITY = 10;

    public ArrayList(int capacity) {
        int initCapacity = Math.max(DEFAULT_CAPACITY, capacity);
        elements = (E[])new Object[initCapacity];
    }

    public ArrayList() {
        this(DEFAULT_CAPACITY);
    }

    @Override
    public void clear() {
        for (int i = 0; i < size; i++) {
            elements[i] = null;
        }
        size = 0;
    }


    @Override
    public E get(int index) {
        rangeCheck(index);
        return elements[index];
    }

    @Override
    public E set(int index, E element) {
        rangeCheck(index);
        E oldValue = elements[index];
        elements[index] = element;
        return oldValue;
    }

    /**
     * 在index 为位置插入一个元素
     */
    public void add(int index, E element) {
        rangeCheckforAdd(index);
        expandCapacity(index+1);
        System.arraycopy(elements, index, elements, index + 1, size - index);
        elements[index] = element;
        size++;
    }

    @Override
    public E remove(int index) {
        rangeCheck(index);
        E oldValue = elements[index];
        System.arraycopy(elements, index + 1, elements, index, size - 1 - index);
        elements[--size] = null;
        return oldValue;
    }

    @Override
    public int indexOf(E element) {
        if (element == null) {
            for (int i = 0; i < size; i++) {
                if (elements[i] == null) return i;
            }
        }else {
            for (int i = 0; i < size; i++) {
                if (element.equals(elements[i])) return i;
            }
        }
        return ELEMENT_NOT_FOUND;
    }


    private void expandCapacity(int capacity) {
        int oldCapacity = elements.length;
        if (oldCapacity >= capacity) return;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        E[] newElement = (E[])new Object[newCapacity];
        System.arraycopy(elements, 0, newElement, 0, elements.length);
        elements = newElement;
        System.out.println(oldCapacity + "扩容为" + newCapacity);
    }
}
